package com.chang.bootplus.controller;


import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chang.bootplus.base.annotation.PublicVisit;
import com.chang.bootplus.base.exception.BusException;
import com.chang.bootplus.base.utils.ApiResponse;
import com.chang.bootplus.base.utils.BeanUtil;
import com.chang.bootplus.base.utils.EvaulateMap;
import com.chang.bootplus.controller.execl.DemoOut;
import com.chang.bootplus.controller.storage.local.LocalService;
import com.chang.bootplus.controller.storage.local.LocalYml;
import com.chang.bootplus.entity.School;
import com.chang.bootplus.entity.StuExecl;
import com.chang.bootplus.entity.StuTest;
import com.chang.bootplus.entity.Student;
import com.chang.bootplus.mapper.BmiMapper;
import com.chang.bootplus.mapper.StuTestMapper;
import com.chang.bootplus.po.*;
import com.chang.bootplus.service.*;
import com.chang.bootplus.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.ParseException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author chang
 * @since 2022-01-23
 */
@RestController
@Api(tags = {"学生信息"})
@RequestMapping("/student")
public class StudentController {



    @Autowired
    StuExeclService stuExeclService;

    @Autowired
    SchoolService schoolService;

    @Autowired
    LocalYml localYml;

    @Autowired
    LocalService localService;

    @Resource
    StuTestMapper stuTestMapper;

    @Autowired
    StudentService studentService;

    @Autowired
    UserResultmapService userResultmapService;

    @Autowired
    StuTestService stuTestService;

    @Autowired
    LocalService service;

    @PostMapping("/studentTestTime")
    @ApiOperation(httpMethod = "POST", value = "拿到学生的各个测试时间")
    public ApiResponse<StudentTimesVO> testStudentTimeDisplay(@RequestBody StudentForTimeStuIdPO po){
        return studentService.testStudentTimeDisplay(po);
    }

//    @ApiOperation(value = "存储学生头像")
//    @ApiImplicitParams({
//            @ApiImplicitParam(
//                    name = "file",
//                    value = "文件",
//                    required = true,
//                    dataType = "__File"
//            ),
//            @ApiImplicitParam(
//                    name = "stuId",
//                    value = "学生学号",
//                    defaultValue = "1710621000"
//            )
//    })
//    @PostMapping("/uploadImg")
//    public ApiResponse<Void> uploadImg(@RequestParam(value = "file") MultipartFile file,String stuId){
//        service.uploadFile(file,"dodo",stuId);
//        return new ApiResponse().setReMsg("存储成功");
//    }



    @PublicVisit
    @PostMapping("/binding")
    @ApiOperation(httpMethod = "POST", value = "用户绑定")
    public ApiResponse binding(@RequestBody StudentLoginPO po){
        List<Student> list = studentService.list(new LambdaQueryWrapper<Student>().eq(Student::getStuId, po.getStuId()).eq(Student::getUsername, po.getUsername()));
        if (list.size()==0) return new ApiResponse().setReMsg("该学生还未录入系统").setReCode("100");
        for (Student t:list){
            if (!t.getOpenId().equals("0")&&!t.getOpenId().equals(po.getOpenId())){
                return new ApiResponse().setReMsg("该学生已被绑定").setReCode("100");
            }
            if (t==null){
                return new ApiResponse().setReMsg("该学生还未录入系统").setReCode("100");
            }
            t.setOpenId(po.getOpenId());
            studentService.saveOrUpdate(t);
        }
        return new ApiResponse().setReMsg("绑定成功");
    }

    @PublicVisit
    @PostMapping("/deletebinding")
    @ApiOperation(httpMethod = "POST", value = "学生解除绑定")
    public ApiResponse deletebinding(@RequestBody StudentBindPO po){
//        String  username = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
//        if (!username.equals("admin")){
//            throw new BusException("你没有管理员权限");
//        }
        List<Student> list = studentService.list(new LambdaQueryWrapper<Student>().eq(Student::getStuId, po.getStuId()));
        for (Student s:list){
            s.setOpenId("0");
            studentService.updateById(s);
        }
        return new ApiResponse("解绑成功");
    }


    @PublicVisit
    @PostMapping("/verify")
    @ApiOperation(httpMethod = "POST", value = "绑定验证")
    public ApiResponse<Void>  verify(@RequestBody  StudentLoginPO po){
        List<Student> list = studentService.list(new LambdaQueryWrapper<Student>().eq(Student::getStuId, po.getStuId()).eq(Student::getUsername, po.getUsername()));
        if (list.size()==0) return new ApiResponse().setReMsg("该学生还未录入系统").setReCode("100");
        for (Student s: list){
            if (s==null){
                return new ApiResponse().setReMsg("该学生还未录入系统").setReCode("100");
            }
            if (s.getOpenId().equals("0")){
                throw new BusException("该学生还未绑定");
            }
        }


        return new ApiResponse().setReMsg("验证成功");
    }

    @PublicVisit
    @PostMapping("/caculateRank")
    @ApiOperation(httpMethod = "POST", value = "获得年级排名")
    public ApiResponse<Void>  verify(@RequestBody  StudentRankPO po){
        List<Student> list3 = studentService.list(new LambdaQueryWrapper<Student>().eq(Student::getStuId, po.getStuId()));
        List<Student> collect = list3.stream().sorted(Comparator.comparing(Student::getGmtCreate).reversed()).collect(Collectors.toList());
        Student one1=collect.get(0);

        //获取成绩
        List<StuTest> list2 = stuTestService.list(new LambdaQueryWrapper<StuTest>().like(StuTest::getGmtCreate, po.getTestTime()).eq(StuTest::getStuId, one1.getStuId()));
        list2=list2.stream().sorted(Comparator.comparing(StuTest::getGmtCreate).reversed()).collect(Collectors.toList());
        // 拿到当前测试成绩
        StuTest one = list2.get(0);

        String schoolName = one1.getSchoolName();
        String gradeId="1"+po.getGrade();
        // 拿到对应学校对应年级的学生,并去重
        List<Student> list = studentService.list(new QueryWrapper<Student>().select("distinct stu_id").lambda().eq(Student::getSchoolName, schoolName).eq(Student::getGradeId, gradeId));

        // 获取test表
        LinkedList<StuTest> stuTests = new LinkedList<>();
        list.stream().forEach(t->{
            // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!这里之前有时间限制，即为.like(StuTest::getGmtCreate, po.getTestTime())，后来删除了，没有时间限制一定能找到
            // 这里可能找不到，因为在其他学校出现过，没找到就不加了
                List<StuTest> list1 = stuTestService.list(new LambdaQueryWrapper<StuTest>()
                        .eq(StuTest::getStuId, t.getStuId())
                        .like(StuTest::getGmtCreate, po.getTestTime())
                );
                if (list1.size()>0){
                    list1=list1.stream().sorted(Comparator.comparing(StuTest::getGmtCreate).reversed()).collect(Collectors.toList());
                    stuTests.add(list1.get(0));
                }
        });
        List<StuTest> collect1 = stuTests.stream().filter(t -> t.getScore() != null).collect(Collectors.toList());
        List<StuTest> collect2 = collect1.stream().sorted(Comparator.comparing(StuTest::getScore).reversed()).collect(Collectors.toList());
        List<Integer> collect3 = collect2.stream().map(t -> t.getScore().intValue()).collect(Collectors.toList());

        int rank =one.getScore()==null?null:collect3.indexOf(one.getScore().intValue())+1;
        HashMap<String, Object> map = new HashMap<>();
        map.put("rank",rank);
        String levelStringByScore = EvaulateMap.getLevelStringByScore(one.getScore()==null?null:one.getScore().intValue());
        map.put("level",levelStringByScore);
        return new ApiResponse().setBody(map);
    }

    @PostMapping("/listMaxResult")
    @ApiOperation(httpMethod = "POST",value = "获取最高成绩")
    public ApiResponse<StudentMaxVO> listMax(@RequestBody StudentMaxPO po){
        EvaulateMap evaulateMap = new EvaulateMap(1);
        StudentMaxVO studentMaxVO = new StudentMaxVO();
       studentMaxVO.setVital(evaulateMap.getMaxScore(po.getSex(),po.getGradeId(),1)==null?null:evaulateMap.getMaxScore(po.getSex(),po.getGradeId(),1).intValue());
       studentMaxVO.setTestFifty(evaulateMap.getMaxScore(po.getSex(),po.getGradeId(),2));
       studentMaxVO.setTestSitRech(evaulateMap.getMaxScore(po.getSex(),po.getGradeId(),3));
       studentMaxVO.setTestSkip(evaulateMap.getMaxScore(po.getSex(),po.getGradeId(),4)==null?null:evaulateMap.getMaxScore(po.getSex(),po.getGradeId(),4).intValue());
       studentMaxVO.setTestSitup(evaulateMap.getMaxScore(po.getSex(),po.getGradeId(),5)==null?null:evaulateMap.getMaxScore(po.getSex(),po.getGradeId(),5).intValue());
       studentMaxVO.setTestRun(evaulateMap.getMaxScore(po.getSex(),po.getGradeId(),6));
        return new ApiResponse<>(studentMaxVO);
    }


    @PostMapping("/listresult")
    @ApiOperation(httpMethod = "POST",value = "获取成绩页面信息")
    public ApiResponse<StudentResultVO> listresult(@RequestBody StudentResultPO po){
        // 获取时间
        List<Student> list1 = studentService.list(new LambdaQueryWrapper<Student>().eq(Student::getStuId, po.getStuId()).like(Student::getGmtCreate, po.getTime()));
        List<Student> collect = list1.stream().sorted(Comparator.comparing(Student::getGmtCreate).reversed()).collect(Collectors.toList());
        Student one=collect.get(0);

        // dasdas
        StudentResultVO studentResultVO = BeanUtil.beanA2beanB(one, StudentResultVO.class);

        // 查到分数
        List<StuTest> list = stuTestService.list(new LambdaQueryWrapper<StuTest>().like(StuTest::getGmtCreate,po.getTime()).eq(StuTest::getStuId, po.getStuId()));
        if (list.size()==0){
            throw new BusException("该学生还没有成绩");
        }
        StuTest stuTest = list.get(0);
        String[] temp={"一","二","三","四","五","六",};
        studentResultVO.setGradeId(one.getGradeId().substring(1));
        studentResultVO.setClassName(temp[new Integer(one.getClassId().substring(1,2))-1]+"年级"+new Integer(one.getClassId().substring(2)).toString().substring(1)+"班");
        studentResultVO.setVital(stuTest.getVital());
        studentResultVO.setTestFifty(stuTest.getTestFifty());
        studentResultVO.setTestSitRech(stuTest.getTestSitRech());
        Integer testSkip = stuTest.getTestSkip();
        if (testSkip!=null){
            testSkip = testSkip >100 ? 100 : testSkip;
        }
        // 成绩 dsdsd
        studentResultVO.setVitalTest(one.getVital());
        studentResultVO.setTestFiftyTest(one.getTestFifty());
        studentResultVO.setTestSitRechTest(one.getTestSitRech());
        studentResultVO.setTestSkipTest(one.getTestSkip());
        studentResultVO.setTestSitupTest(one.getTestSitup());
        studentResultVO.setTestRunTest(one.getTestRun());

        //分数
        studentResultVO.setTestSkip(testSkip);
        studentResultVO.setTestSitup(stuTest.getTestSitup());
        studentResultVO.setTestRun(stuTest.getTestRun());
        studentResultVO.setScore(stuTest.getScore()==null? null:stuTest.getScore().intValue());
        studentResultVO.setResultOther(stuTest.getResultOther());
        studentResultVO.setLastTime(stuTest.getGmtCreate().toLocalDate().format(DateTimeFormatter.ofPattern("YYYY年MM月dd日")));
        EvaulateMap evaulateMap = new EvaulateMap();
        studentResultVO.setResultEvaluate(evaulateMap.getEvaulate(stuTest.getTestFifty(),one.getBmi(),stuTest.getVital(),stuTest.getTestSitup(),stuTest.getTestSkip(),stuTest.getTestRun(),stuTest.getTestSitRech(),one.getSex(),one.getGradeId()));
        studentResultVO.setExpectSuggest(evaulateMap.getSueggest(stuTest.getTestFifty(),one.getBmi(),stuTest.getVital(),stuTest.getTestSitup(),stuTest.getTestSkip(),stuTest.getTestRun(),stuTest.getTestSitRech(),one.getSex(),one.getGradeId()));
        return  new ApiResponse<>(studentResultVO);
    }


    @PostMapping("/getLevel")
    @ApiOperation(httpMethod = "POST",value = "获取分数对应等级信息")
    public  ApiResponse<Void> getlevel(@RequestBody Integer score){
        if (score>=90&&score<=100){
            return new ApiResponse().setReMsg("优秀");
        }
        if (score>=80&&score<=89){
            return new ApiResponse().setReMsg("良好");
        }
        if (score>=60&&score<=79){
            return new ApiResponse().setReMsg("及格");
        }
        return new ApiResponse().setReMsg("不及格");
    }


    @PostMapping("/calculation")
    @ApiOperation(httpMethod = "POST",value = "成绩计算")
    public  ApiResponse<CalculateVO> calculation(@RequestBody CalculatePO po){
        return  userResultmapService.calculate(po);
    }


    @PostMapping("/calculation/testall")
    @ApiOperation(httpMethod = "POST",value = "计算总分")
    public  ApiResponse<CalculateAllVO> calculationall(@RequestBody CalculateAllPO po){
        return  userResultmapService.calculateAll(po);
    }

    @PostMapping("/getAllProjectIds")
    @ApiOperation(httpMethod = "POST",value = "获得学生所有的项目id")
    public ApiResponse<ProjectVO> getAllId(@RequestBody ProjectPO po){
        Integer integer = new Integer(po.getGradeId());
        List<Integer> list = new LinkedList<>();
        list.add(7);
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        ProjectVO projectVO = new ProjectVO();
        if (integer<=2){
            projectVO.setProjectIds(list);
            return new ApiResponse<>(projectVO);
        }else if (integer<=4){
            list.add(5);
            projectVO.setProjectIds(list);
            return new ApiResponse<>(projectVO);
        }else {
            list.add(5);
            list.add(6);
            projectVO.setProjectIds(list);
            return new ApiResponse<>(projectVO);
        }
    }



    @PostMapping("/getHistoryTime")
    @ApiOperation(httpMethod = "POST",value = "获取历史成绩时间")
    public  ApiResponse<Void> getHistoryTime(@RequestBody StudentResultPO po){
        String stuId = po.getStuId();
        List<StuTest> list = stuTestService.list(new LambdaQueryWrapper<StuTest>().eq(StuTest::getStuId, po.getStuId()));
        HashSet<String> set = new HashSet<>();
        list.stream().forEach(t->{
            String temp = t.getGmtCreate().toLocalDate().format(DateTimeFormatter.ofPattern("YYYY-MM-dd"));
            set.add(temp);
        });
        List<String> collect = set.stream().sorted().collect(Collectors.toList());
        HashMap<String, Object> map = new HashMap<>();
        map.put("Timelist",collect);
        return new ApiResponse().setBody(map);
    }


    @PostMapping("/getSorceByTime")
    @ApiOperation(httpMethod = "POST",value = "根据时间获取总分")
    public  ApiResponse<Void> getSroceHistoryTime(@RequestBody TimePO po) throws ParseException {

        List<StuTest> list = stuTestService.list(new LambdaQueryWrapper<StuTest>().eq(StuTest::getStuId,po.getStuId()).like(StuTest::getGmtCreate, po.getTime()));
        list.sort((t1,t2)->{
            return t1.getGmtCreate().toString().compareTo(t2.getGmtCreate().toString());
        });
        Integer  temp=list.get(0).getScore()==null?null:list.get(0).getScore().intValue();
        HashMap<String, Object> map = new HashMap<>();
        map.put("score",temp);
        return new ApiResponse().setBody(map);

    }


    @PostMapping("/getHistoryResults")
    @ApiOperation(httpMethod = "POST",value = "获取历史成绩信息")
    public  ApiResponse<ResultVO> getHistoryResult(@RequestBody ResultPO po){

        return  stuTestService.getHistoryResult(po);
    }

    @PostMapping("/newsTopMessage")
    @ApiOperation(httpMethod = "POST",value = "获取资讯栏用户成绩信息展示")
    public  ApiResponse<TopMessageVO> topMessage(@RequestBody CheckStatusPO po){
        return studentService.topMessage(po);
    }

    // 根据当前用户名筛选
//    @Transactional
    @PostMapping("/selectScore")
    @ApiOperation(httpMethod = "POST",value = "筛选成绩信息    管理员不传学校为查所有")
    public ApiResponse<DemoOut> selectScore(@RequestBody SelectPO po){
        String  username = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        School one = schoolService.getOne(new LambdaQueryWrapper<School>().eq(School::getNickName, username));
        List<DemoOut> demoOuts = new LinkedList<>();
        List<String> gradeList=new LinkedList<>(Arrays.asList(" ","一","二","三","四","五","六"));
                //三年级转化为   3 ;
        String grade=po.getGrade()==null ? null:"1" + gradeList.indexOf(po.getGrade().substring(0,1));

        // 12班转化为  13 10 12
        String className=po.getClassName()==null? null: po.getClassName().substring(0,po.getClassName().length()-1); // 拿到2数字
        if (className!=null){
            if (new Integer(className)<10){// 小于10补前导0
                className="0"+className;
            }
        }
        String classId=className==null ? null :"01"+className;
        List<Student> students=new LinkedList<>();

        List<StuExecl> list2 = stuExeclService.list(new LambdaQueryWrapper<StuExecl>().eq(!(one.getSchoolName().equals("admin")&&po.getSchoolName()==null),StuExecl::getSchoolName, po.getSchoolName()));
        String s1=null;
        if (po.getDateName()==null){
            List<LocalDateTime> collect = list2.stream().sorted(Comparator.comparing(StuExecl::getGmtCreate).reversed()).map(StuExecl::getGmtCreate).collect(Collectors.toList());
            s1 = collect.get(0).toString();// 排序后拿到最新的
        }
        // 不分页,已经去重
        int  countAll = studentService.count(new QueryWrapper<Student>()
                .select("distinct stu_id").lambda()
                .like(po.getStuId()!=null,Student::getStuId,po.getStuId())
                .eq(grade!=null,Student::getGradeId,grade)
                .like(po.getUsername()!=null,Student::getUsername,po.getUsername())
                .eq(po.getDateName()==null,Student::getGmtCreate,s1) // 没有就查最新的
                .like(po.getDateName()!=null,Student::getGmtCreate,po.getDateName())// 有date参数模糊查询
                .like(classId!=null,Student::getClassId,classId).eq(!(one.getSchoolName().equals("admin")&&po.getSchoolName()==null),Student::getSchoolName,po.getSchoolName()));
        // 分页   100   /10 --》 10
        Page<Student> studentPage = new Page<>(po.getPageNumber(),po.getPageSize());
        // 为null的话则为最新的，不为null的话查询当前的成绩
        Page<Student> page = studentService.page(studentPage, new QueryWrapper<Student>()
                .select("distinct stu_id").lambda()
                .like(po.getStuId()!=null,Student::getStuId,po.getStuId())
                .eq(grade!=null,Student::getGradeId,grade)
                .like(po.getUsername()!=null,Student::getUsername,po.getUsername())
                .eq(po.getDateName()==null,Student::getGmtCreate,s1) // 没有就查最新的
                .like(po.getDateName()!=null,Student::getGmtCreate,po.getDateName())// 有date参数模糊查询
                .like(classId!=null,Student::getClassId,classId).eq(!(one.getSchoolName().equals("admin")&&po.getSchoolName()==null),Student::getSchoolName,po.getSchoolName()));

        students=BeanUtil.listA2ListB(page.getRecords(),Student.class);
        System.out.println(students+"-----------------------");
        LinkedList<Student> students1 = new LinkedList<>();
        students.stream().forEach(t->{
            List<Student> collect = studentService.list(new LambdaQueryWrapper<Student>().eq(Student::getStuId, t.getStuId())).stream().sorted(Comparator.comparing(Student::getGmtCreate).reversed()).collect(Collectors.toList());
            students1.add(collect.get(0));
        });


        students1.forEach(t->{
            List<StuTest> list=new LinkedList<>();
            if (po.getDateName()==null){
                  list = stuTestService.list(new LambdaQueryWrapper<StuTest>().eq(StuTest::getStuId,t.getStuId()).orderByDesc(StuTest::getGmtCreate));
            }else {
                  list = stuTestService.list((new LambdaQueryWrapper<StuTest>().eq(StuTest::getStuId,t.getStuId()).like(StuTest::getGmtCreate,po.getDateName())));
            }

            StuTest temp=list.size()>0 ? list.get(0): null;
            DemoOut demoOut = BeanUtil.beanA2beanB(t,DemoOut.class);
            if (temp!=null){
                String sex=t.getSex()== 0 ? "女": "男";
                demoOut.setStuId(t.getStuId());
                demoOut.setSex(sex);
                demoOut.setBmiScore(temp.getBmi());
                demoOut.setBmiLevel(EvaulateMap.getLevelStringByScore(temp.getBmi())==null? null:EvaulateMap.getLevelStringByScore(temp.getBmi()));
                demoOut.setVitalScore(temp.getVital());
                demoOut.setVitalLevel(EvaulateMap.getLevelStringByScore(temp.getVital()));
                demoOut.setTestFiftyScore(temp.getTestFifty());
                demoOut.setTestFiftyLevel(EvaulateMap.getLevelStringByScore(temp.getTestFifty()));
                demoOut.setTestSitRechScore(temp.getTestSitRech());
                demoOut.setTestSitRechLevel(EvaulateMap.getLevelStringByScore(temp.getTestSitRech()));
                demoOut.setTestSkipScore(temp.getTestSkip());
                demoOut.setTestSkipLevel(EvaulateMap.getLevelStringByScore(temp.getTestSkip()));
                demoOut.setTestSitupScore(temp.getTestSitup());
                demoOut.setTestSitupLevel(EvaulateMap.getLevelStringByScore(temp.getTestSitup()));
                demoOut.setTestRunScore(temp.getTestRun());
                demoOut.setTestRunLevel(EvaulateMap.getLevelStringByScore(temp.getTestRun()));
                demoOut.setOtherScore(temp.getResultOther());
                if (temp.getScore()==null){
                    demoOut.setMinScore(null);
                    demoOut.setAllScore(null);
                }else if(temp.getResultOther()==null){
                    demoOut.setMinScore((double) (temp.getScore()));
                    demoOut.setAllScore(temp.getScore().doubleValue());
                }
                else {
                    try {
                        demoOut.setMinScore((double) (temp.getScore() - temp.getResultOther()));
                        demoOut.setAllScore(temp.getScore().doubleValue());
                    }catch (Exception e){
                        throw new BusException(t.getId()+"该学生无成绩");
                    }
                }
                demoOut.setAllLevel(EvaulateMap.getLevelStringByScore( temp.getScore()==null?null:temp.getScore().intValue() ));
                demoOuts.add(demoOut);
            }
        });
        return new ApiResponse(demoOuts,new Long(demoOuts.size()),new Long(countAll));
    }

    // 根据当前用户名导出
//    @Transactional
    @PostMapping("/outScore")
    @ApiOperation(httpMethod = "POST",value = "导出成绩信息")
    public ApiResponse<Void> outScore(@RequestBody SelectPO po){
        String  username = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        School one = schoolService.getOne(new LambdaQueryWrapper<School>().eq(School::getNickName, username));
        List<DemoOut> demoOuts = new LinkedList<>();
        List<String> gradeList=new LinkedList<>(Arrays.asList(" ","一","二","三","四","五","六"));
        //三年级转化为   3 ;
        String grade=po.getGrade()==null ? null:"1" + gradeList.indexOf(po.getGrade().substring(0,1));
        // 12班转化为  13 10 12
        String className=po.getClassName()==null? null: po.getClassName().substring(0,po.getClassName().length()-1); // 拿到2数字
        if (className!=null){
            if (new Integer(className)<10){// 小于10补前导0
                className="0"+className;
            }
        }
        String classId=className==null ? null:"01"+className;
        List<Student> students=new LinkedList<>();


        List<StuExecl> list2 = stuExeclService.list(new LambdaQueryWrapper<StuExecl>().eq(!(one.getSchoolName().equals("admin")&&po.getSchoolName()==null),StuExecl::getSchoolName, po.getSchoolName()));
        String s1=null;
        if (po.getDateName()==null){
            List<LocalDateTime> collect = list2.stream().sorted(Comparator.comparing(StuExecl::getGmtCreate).reversed()).map(StuExecl::getGmtCreate).collect(Collectors.toList());
            s1 = collect.get(0).toString();// 排序后拿到最新的
        }

        students = studentService.list(new QueryWrapper<Student>()
                .select("distinct stu_id").lambda()
                .like(po.getStuId()!=null,Student::getStuId,po.getStuId())
                .eq(grade!=null,Student::getGradeId,grade)
                .like(po.getUsername()!=null,Student::getUsername,po.getUsername())
                .eq(po.getDateName()==null,Student::getGmtCreate,s1) // 没有就查最新的
                .like(po.getDateName()!=null,Student::getGmtCreate,po.getDateName())// 有date参数模糊查询
                .like(classId!=null,Student::getClassId,classId).eq(!(one.getSchoolName().equals("admin")&&po.getSchoolName()==null),Student::getSchoolName,po.getSchoolName()));

        System.out.println(students);
        LinkedList<Student> students1 = new LinkedList<>();
        students.stream().forEach(t->{
            List<Student> collect = studentService.list(new LambdaQueryWrapper<Student>().eq(Student::getStuId, t.getStuId())).stream().sorted(Comparator.comparing(Student::getGmtCreate).reversed()).collect(Collectors.toList());
            students1.add(collect.get(0));
        });

        students1.forEach(t->{
            List<StuTest> list=new LinkedList<>();
            if (po.getDateName()==null){
                list = stuTestService.list(new LambdaQueryWrapper<StuTest>().eq(StuTest::getStuId,t.getStuId()).orderByDesc(StuTest::getGmtCreate));
            }else {
                list = stuTestService.list((new LambdaQueryWrapper<StuTest>().eq(StuTest::getStuId,t.getStuId()).like(StuTest::getGmtCreate,po.getDateName())));
            }

            StuTest temp=list.size()>0 ? list.get(0): null;
            DemoOut demoOut = BeanUtil.beanA2beanB(t,DemoOut.class);
            if (temp!=null){
                String sex=t.getSex()== 0 ? "女": "男";
                demoOut.setSex(sex);
                demoOut.setBmiScore(temp.getBmi());
                demoOut.setBmiLevel(EvaulateMap.getLevelStringByScore(temp.getBmi())==null? null:EvaulateMap.getLevelStringByScore(temp.getBmi()));
                demoOut.setVitalScore(temp.getVital());
                demoOut.setVitalLevel(EvaulateMap.getLevelStringByScore(temp.getVital()));
                demoOut.setTestFiftyScore(temp.getTestFifty());
                demoOut.setTestFiftyLevel(EvaulateMap.getLevelStringByScore(temp.getTestFifty()));
                demoOut.setTestSitRechScore(temp.getTestSitRech());
                demoOut.setTestSitRechLevel(EvaulateMap.getLevelStringByScore(temp.getTestSitRech()));
                demoOut.setTestSkipScore(temp.getTestSkip());
                demoOut.setTestSkipLevel(EvaulateMap.getLevelStringByScore(temp.getTestSkip()));
                demoOut.setTestSitupScore(temp.getTestSitup());
                demoOut.setTestSitupLevel(EvaulateMap.getLevelStringByScore(temp.getTestSitup()));
                demoOut.setTestRunScore(temp.getTestRun());
                demoOut.setTestRunLevel(EvaulateMap.getLevelStringByScore(temp.getTestRun()));
                demoOut.setOtherScore(temp.getResultOther());
                if (temp.getScore()==null){
                    demoOut.setMinScore(null);
                    demoOut.setAllScore(null);
                }else if(temp.getResultOther()==null){
                    demoOut.setMinScore((double) (temp.getScore()));
                    demoOut.setAllScore(temp.getScore().doubleValue());
                }
                else {
                    try {
                        demoOut.setMinScore((double) (temp.getScore() - temp.getResultOther()));
                        demoOut.setAllScore(temp.getScore().doubleValue());
                    }catch (Exception e){
                        throw new BusException(t.getId()+"该学生无成绩");
                    }
                }

                demoOut.setAllLevel(EvaulateMap.getLevelStringByScore(temp.getScore()==null?null:temp.getScore().intValue()));
                demoOuts.add(demoOut);
            }
        });

        String fileName =System.currentTimeMillis() + ".xlsx";
        String uploadPath="/www/home/project/do_one_do/excel/"+fileName;
//        String uploadPath="C:/Users/jokehe/Desktop/t/"+fileName;
        // 这里 需要指定写用哪个class去写，然后写到第一个sheet，名字为模板 然后文件流会自动关闭
        // 如果这里想使用03 则 传入excelType参数即可
        EasyExcel.write(uploadPath, DemoOut.class)
                .sheet("模板")
                .doWrite(() -> {
                    // 分页查询数据
                    return demoOuts;
                });
        String downloadPath=localYml.getVisitAddress2()+"/do_one_do/excel/"+fileName;
//        String downloadPath="C:/Users/jokehe/Desktop/t/"+fileName;
//        System.out.println(demoOuts.size()+"--------------------------------------------->");
        // 查到多少导出多少
        return new ApiResponse(demoOuts).setReMsg(downloadPath);
    }
}

